from flask import Flask,session
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_wtf.csrf import generate_csrf,CSRFProtect
from flask_session import Session
from flask import session,render_template
from flask import g

from config import config_dict
import logging
from logging.handlers import RotatingFileHandler
from info.utits.common import do_index_class,user_login_data

db =SQLAlchemy()
def setup_log(config_name):
    """记录日志函数"""
    # 获取配置类
    config_class = config_dict[config_name]

    # 设置日志的记录等级
    logging.basicConfig(level=config_class.LOG_LEVEL)  # 调试debug级

    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小(100M)、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)

    # 创建日志记录的格式: 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')

    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)

    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)

redis_store =None # type:StrictRedis
# app工厂方法
def create_app(config_name):
    setup_log(config_name)
    app = Flask(__name__)
    config_class = config_dict[config_name]
    app.config.from_object(config_class)
    db.init_app(app)
    global  redis_store
    redis_store =StrictRedis(host=config_class.REDIS_HOST, port=config_class.REDIS_PORT, db=config_class.REDIS_NUM)
    csrf = CSRFProtect(app)
    # 使用钩子函数同意设置cookie
    @app.after_request
    def set_csrftoken(response):
        csrf_token=generate_csrf()
        response.set_cookie("csrf_token",csrf_token)
        return response
    # 404页面返回
    @app.errorhandler
    @user_login_data
    def error_handler(error):
        user=g.user
        data = {
            "user_info":user.to_dict() if user else None
        }
        return render_template("news/404.html",data=data)
    # 添加过滤器
    app.add_template_filter(do_index_class,"do_index_class")
    Session(app)
    # 注册蓝图
    from info.moduls.index import index_bp
    app.register_blueprint(index_bp)

    from info.moduls.passport import passport_bp
    app.register_blueprint(passport_bp)

    from info.moduls.news import news_bp
    app.register_blueprint(news_bp)

    return app